package com.bos.service.impl;

import java.sql.Timestamp;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bos.bean.DecidedZone;
import com.bos.bean.Noticebill;
import com.bos.bean.Staff;
import com.bos.bean.User;
import com.bos.bean.Workbill;
import com.bos.crm.CrmService;
import com.bos.dao.DecidedDao;
import com.bos.dao.NoticebillDao;
import com.bos.dao.WorkbillDao;
import com.bos.service.NoticebillService;

@Service
@Transactional
public class NoticebillServiceImpl implements NoticebillService {

	@Autowired
	private NoticebillDao noticeDao;

	@Autowired
	private CrmService crmService;
	
	@Autowired
	private DecidedDao decidedDao;
	
	@Autowired
	private WorkbillDao workbillDao;
	
	
	public void save(Noticebill model) {
		//给业务通知单设置  当前登录的用户
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute("userInfo");
		model.setUser(user);
		noticeDao.insert(model);
		//获取地址
		String address = model.getPickaddress();
		//根据地址查询定区的Id
		String decidedId = crmService.findDecidedIdByAddr(address);
		if(decidedId != null && !decidedId.isEmpty()){
			//根据定区的Id查询  定区负责的快递员
			DecidedZone decidedZone = decidedDao.findById(decidedId);
			Staff staff = decidedZone.getStaff();
			model.setStaff(staff);
			//创建快递员的工单
			Workbill workbill = new Workbill();
			workbill.setStaff(staff);
			workbill.setType(Workbill.TYPE_1);
			workbill.setPickstate(Workbill.PICKSTATE_NEW);
			//设置创建时间
			workbill.setBuildtime(new Timestamp(System.currentTimeMillis()));
			//设置追单次数 为0
			workbill.setAttachbilltimes(0);
			//设置备注
			workbill.setRemark(model.getRemark());
			//设置业务通知单的关联
			workbill.setNoticebill(model);
			//自动分单
			model.setOrdertype(Noticebill.ORDERTYPE_AUTO);
			//保存工单
			workbillDao.insert(workbill);
			//发短信   调用一下短信平台的 API就可以了
		}else{
			//手动分单
			model.setOrdertype(Noticebill.ORDERTYPE_MAN);
		}
	}
	
}
